//
//  YFSelectedTagView.m
//  YFToolsDemo
//
//  Created by apple on 2018/5/5.
//  Copyright © 2018年 BigShow. All rights reserved.
//
#import "CollectionViewCell.h"
#import "YFSelectedTagView.h"
#import "CollectionHeaderView.h"
#import "UICollectionViewLeftAlignedLayout.h"
#import "YFBuyCountViewCell.h"

#define kControllerHeaderViewHeight                90
#define kControllerHeaderToCollectionViewMargin    0
#define kCollectionViewCellsHorizonMargin          12
#define kCollectionViewCellHeight                  25
#define kCollectionViewItemButtonImageToTextMargin 5

#define kCollectionViewToTopMargin                 15
#define kCollectionViewToLeftMargin                10
#define kCollectionViewToBottomtMargin             15
#define kCollectionViewToRightMargin               10

#define kCellImageToLabelMargin                    10
#define kCellBtnCenterToBorderMargin               10

typedef void(^ISLimitWidth)(BOOL yesORNo,id data);
static NSString * const kCellIdentifier           = @"CellIdentifier";
static NSString * const kCellIdentifierCount      = @"CellIdentifier2";
static NSString * const kHeaderViewCellIdentifier = @"HeaderViewCellIdentifier";

@interface YFSelectedTagView ()<UICollectionViewDelegate, UICollectionViewDataSource>

// @[@"12","00",@"13"];
@property (nonatomic, strong) NSMutableArray *selectedStringArr;

@end
@implementation YFSelectedTagView

- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout {
    if (self =[super initWithFrame:frame collectionViewLayout:layout]) {
        [self makeView];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self makeView];
        
    }
    return self;
}

- (void)makeView {
    
    self.count = 1; // 默认就是1个
    
    { // 测试
        /*
        NSMutableArray * array1 = [@[@"推荐",@"热点",@"汽车",@"财经频道",@"热点",@"社会",@"明星八卦",@"IT科技",@"移动互联网",@"金融",@"大数据",@"股票期货",@"食品安全新闻",@"自定义标签"]mutableCopy];
        [self.dataSourceArr addObject:array1];
        NSMutableArray * array2 = [@[@"推荐",@"热点",@"汽车",@"财经频道",@"热点",@"社会",@"明星八卦",@"IT科技",@"移动互联网",@"金融",@"大数据",@"股票期货",@"食品安全新闻食品食品安全"]mutableCopy];
        [self.dataSourceArr addObject:array2];
        
        self.titleArr = @[@"订阅", @"为订阅"];
         //*/
    }
    
    self.backgroundColor = [UIColor whiteColor];

    [self registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:kCellIdentifier];
    [self registerClass:[YFBuyCountViewCell class] forCellWithReuseIdentifier:kCellIdentifierCount];

    [self registerClass:[CollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kHeaderViewCellIdentifier];
    self.showsHorizontalScrollIndicator = NO;
    self.scrollsToTop = NO;
    self.scrollEnabled = YES;
    
    self.delegate = self;
    self.dataSource = self;
}
#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    // 3
    NSLog(@"self.goodsTypeArr.count = %lu", (unsigned long)self.goodsTypeArr.count);
    return self.goodsTypeArr.count + 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    // 2
    if (section == self.goodsTypeArr.count) {
        return 1;
    }else {

        YFGoodsTypeModel *model =  self.goodsTypeArr[section];
        NSLog(@"model.dataArr.count = %lu", (unsigned long)model.dataArr.count);
        return model.dataArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == self.goodsTypeArr.count) {
        YFBuyCountViewCell *countCell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellIdentifierCount forIndexPath:indexPath];
        kWeakSelf
        countCell.didSelectedBlock = ^(NSInteger buyCount) {
            NSLog(@"buyCount = %d", buyCount);
            weakSelf.count = buyCount;
        };
        return countCell;
    }else {
        CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kCellIdentifier forIndexPath:indexPath];
        cell.titleLabel.frame = CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height);
        
        
        YFGoodsTypeModel *model =  self.goodsTypeArr[indexPath.section];
        YFGoodsTypeSubModel *subModel = model.dataArr[indexPath.row];

        cell.model = subModel;
        return cell;
    }
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    // 判断是否可以点击
    YFGoodsTypeModel *selectedTypeModel = self.goodsTypeArr[indexPath.section];
    YFGoodsTypeSubModel *selectedSubModel = selectedTypeModel.dataArr[indexPath.row];
    if (selectedSubModel.state.intValue == 0) {
        return;
    }
    
    // 判断数据源里indexPath.section 行里的选中状态变成一般状态
    for (YFGoodsTypeSubModel *subModel in selectedTypeModel.dataArr) {
        if (subModel.state.intValue == 2) {
            subModel.state = @1;
        }
    }
    // 将点击的变成选中状态
    selectedSubModel.state = @2;
    
    // 只有所有规格都选择, 才需要回调
    if (self.selectedArr.count == self.goodsTypeArr.count) {

        if (self.didSelectedBlock) {  // 这里只拼接id
            // 拼接id
            NSString *itemID = @"";
            for (int i = 0; i < self.selectedArr.count; i++) {
                YFGoodsTypeSubModel *subModel = self.selectedArr[i];
                if (i==0) {
                    itemID = [itemID stringByAppendingString:subModel.item_id];
                }else {
                    itemID = [itemID stringByAppendingString:[NSString stringWithFormat:@"_%@", subModel.item_id]];
                }
            }
            
            // 查找id
            self.model = nil;
            for (YFGoodsPriceModel *model in self.goodsPriceArr) {
                NSLog(@"for - key = %@", model.key);
                if ([model.key isEqualToString:itemID]) {
                    self.model = model;
                }
            }
            
            if (self.model) {
                NSLog(@"didSelectedBlock ==马上回调");
                self.didSelectedBlock(self.model,self.selectedArr);
            }else { // 没有这个规格的商品
                
            }
            NSLog(@"itemID = %@", itemID);
            
        }
        
    }else { // 判断是否可选
        // 先测试 点击第一行  应该是选中的有哪些
        NSLog(@"item_id = %@", selectedSubModel.item_id);
        // 12_00   00_12_00_17
        //*
        for (int i = 0; i < self.goodsTypeArr.count; i++) {
            YFGoodsTypeModel *typeModel = self.goodsTypeArr[i];
            
            for (int j = 0; j < typeModel.dataArr.count; j++) {
                YFGoodsTypeSubModel *subModel = typeModel.dataArr[j];
                // 如果跟选中的同一行, 状态不变
                NSString *selectedStr = self.selectedStringArr[i];
                if (![selectedStr isEqualToString:@"00"]) {
                    // 当前行有选中项,无需判断了,原来是什么状态,现在就是什么状态
                    
                }else {// 跟选中行不是同一行, 下步判断
                    // 12_00
                    // 将subModel 的id:13, 替换对应的字符串,比如subModel是第一行:12_13
                    NSMutableArray *selectedStringArr = [NSMutableArray arrayWithArray:self.selectedStringArr];
                    [selectedStringArr replaceObjectAtIndex:i withObject:subModel.item_id];
                    NSLog(@"selectedStringArr = %@", selectedStringArr);// 12,13
                    
                    BOOL isMatch = NO;
                    // 11_12_00_17 在priceArr中查找, 不是0的数字,都能匹配到, 就说明这个按钮可以点击
                    for (YFGoodsPriceModel *priceModel in self.goodsPriceArr) {
                        // 将字符串切成数组 11_12_16_17
                        NSArray *arr = [priceModel.key componentsSeparatedByString:@"_"];
                        NSLog(@"arr = %@", arr);
                        BOOL isSubModelMatch = YES; // 默认是匹配的
                        // 挨个对比
                        for (int m = 0; m < arr.count; m++) {
                            NSString *priceStr = arr[m]; // 11_12_16_17
                            NSString *str = selectedStringArr[m]; // 11_12_00_17
                            
                            if ([str isEqualToString:@"00"]) { // 00 不需要比较
                            }else if ([priceStr isEqualToString:str]) { // 相同
                            }else { // 不相同
                                isSubModelMatch = NO;
                            }
                        }
                        NSLog(@"isSubModelMatch = %d", isSubModelMatch);

                        if (isSubModelMatch) {
                            isMatch = YES;
                            break;
                        }
                    }
                    
                    NSLog(@"isMatch = %d",isMatch);
                    // 选中状态需要判断吗?
                    if (isMatch) { // 匹配,可点击
                        subModel.state = @1;
                    }else { // 不匹配, 不可点击
                        subModel.state = @0;
                    }
                    
                }
                
            }
        }
         //*/

        /*
        YFGoodsTypeModel *typeModel = self.goodsTypeArr[1];
        for (YFGoodsTypeSubModel *subModel in typeModel.dataArr) {
            NSString *idStr = [NSString stringWithFormat:@"%@_%@", selectedSubModel.item_id, subModel.item_id];

            NSLog(@"idStr = %@", idStr); // 12_13

            // 判断 idStr 在 goodsPriceArr 有没有
            // 有: 这个model设置一般状态
            // 无: 这个model设置无可点击装

            BOOL isExist = NO;
            for (YFGoodsPriceModel *priceModel in self.goodsPriceArr) {
                NSLog(@"key = %@", priceModel.key);
                if ([priceModel.key isEqualToString:idStr]) {
                    isExist = YES;
                    break;
                }
            }
            NSLog(@"是否存在 isExist = %d", isExist);
            if (isExist) {  // 存在就可点击
                subModel.state = @1;
            }else {   // 不存在不可点击
                subModel.state = @0;
            }
        }
        // 拼接选中id
        // 11_12_13
         */
    }
    
    [self printState];
    [self reloadData];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
        

        CollectionHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kHeaderViewCellIdentifier forIndexPath:indexPath];
        if (indexPath.section == self.goodsTypeArr.count) {
            headerView.titleLabel.text = @"购买数量";
        }else {
            YFGoodsTypeModel *model =  self.goodsTypeArr[indexPath.section];
            headerView.titleLabel.text = model.title;
        }
        return (UICollectionReusableView *)headerView;
    }
    return nil;
}


- (float)getCollectionCellWidthText:(NSString *)text{
    float cellWidth;
    CGSize size = [text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18]}];
    
    cellWidth = ceilf(size.width) + kCellBtnCenterToBorderMargin;
    cellWidth = [self checkCellLimitWidth:cellWidth isLimitWidth:nil];
    return cellWidth;
}


- (float)checkCellLimitWidth:(float)cellWidth isLimitWidth:(ISLimitWidth)isLimitWidth {
    float limitWidth = (CGRectGetWidth(self.frame)-kCollectionViewToLeftMargin-kCollectionViewToRightMargin);
    if (cellWidth >= limitWidth) {
        cellWidth = limitWidth;
        isLimitWidth?isLimitWidth(YES,@(cellWidth)):nil;
        return cellWidth;
    }
    isLimitWidth?isLimitWidth(NO,@(cellWidth)):nil;
    return cellWidth;
}

#pragma mark - UICollectionViewDelegateLeftAlignedLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == self.goodsTypeArr.count) {
        return CGSizeMake(75, 25);
    }else {
        // cell 的宽
        YFGoodsTypeModel *model =  self.goodsTypeArr[indexPath.section];
        YFGoodsTypeSubModel *subModel = model.dataArr[indexPath.row];
        
        float cellWidth = [self getCollectionCellWidthText:subModel.item];
        return CGSizeMake(cellWidth, kCollectionViewCellHeight);
    }
}



- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return kCollectionViewCellsHorizonMargin;//cell之间的间隔
}


// header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake([UIScreen mainScreen].bounds.size.width, 25);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    //四周边距
    return UIEdgeInsetsMake(kCollectionViewToTopMargin, kCollectionViewToLeftMargin, kCollectionViewToBottomtMargin, kCollectionViewToRightMargin);
}
#pragma mark - 懒加载
- (NSMutableArray *)selectedArr {
    _selectedArr = [NSMutableArray array];
    for ( YFGoodsTypeModel *testModel in self.goodsTypeArr) {
        for (YFGoodsTypeSubModel *subModel in testModel.dataArr) {
            if (subModel.state.intValue == 2) {
                [_selectedArr addObject:subModel];
            }
        }
    }
    return  _selectedArr;
}


#pragma mark - setter
- (NSArray<YFGoodsPriceModel *> *)goodsPriceArr {
    if (!_goodsPriceArr) {
        _goodsPriceArr = [NSMutableArray array];
    }
    return _goodsPriceArr;
}

- (NSArray<YFGoodsTypeModel *> *)goodsTypeArr {
    if (!_goodsTypeArr) {
        _goodsTypeArr = [NSMutableArray array];
    }
    return _goodsTypeArr;
}

- (NSMutableArray *)selectedStringArr { // @[@"12","00",@"23"]
    // 可选id数组
    NSMutableArray *tempArr =[NSMutableArray array];
    for (int i = 0; i < self.goodsTypeArr.count; i++) {
        YFGoodsTypeModel *typeModel = self.goodsTypeArr[i];
        
        NSString *tempStrID = @"00"; // 找出每行选中的id, 没选中默认就是"00"
        for (YFGoodsTypeSubModel *subModel in typeModel.dataArr) {
            if (subModel.state.intValue == 2) {
                tempStrID = subModel.item_id;
            }
        }
        [tempArr addObject:tempStrID];
    }
    _selectedStringArr = tempArr;

    return _selectedStringArr;
}

#pragma mark -  test
- (void)printState {
    NSLog(@"马上打印状态");

    for ( YFGoodsTypeModel *testModel in self.goodsTypeArr) {
        for (YFGoodsTypeSubModel *subModel in testModel.dataArr) {
            NSLog(@"state = %@", subModel.state);
        }
    }
}



/*
- (void)setGoodsTypeArr:(NSArray<YFGoodsTypeModel *> *)goodsTypeArr {
    _goodsTypeArr = goodsTypeArr;
    NSLog(@"count = %ld", goodsTypeArr.count);
    for (YFGoodsTypeModel *model in goodsTypeArr) {
        [self.titleArr addObject:model.title];

        NSMutableArray *tempArr = [NSMutableArray array];
        for (YFGoodsTypeSubModel *subModel in model.dataArr) {
            [tempArr addObject:subModel.item];
        }
        [self.dataSourceArr addObject:tempArr];
    }
    
}
 */

@end
